package com.example.mock;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: snow_grains
 * @Date: 2022/1/14
 * @Description:
 **/
@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    private static Map<Integer, User> userMap;

    static Map<Integer, User> getUserMap() {
        if (userMap == null) {
            userMap = new HashMap<>();
            userMap.put(1, new User(1, "bai", "man", 15));
            userMap.put(2, new User(2, "Bob", "man", 21));
            userMap.put(3, new User(3, "Lily", "woman", 18));
        }
        return userMap;
    }

    @GetMapping("/user")
    public String findAllUser() {
        String jsonString = JSONObject.toJSONString(getUserMap());
        return jsonString;
    }

    @GetMapping("/user/id")
    public User findUserById(Integer id) {
        return getUserMap().get(id);
    }

    @PostMapping("/user")
    public Map<Integer, User> addUser(@RequestBody User user) {
        Map<Integer, User> userMap = getUserMap();
        userMap.put(user.getId(), user);
        return userMap;
    }

    @PostMapping("/user/save")
    public String saveUser(@RequestBody User user) {
        String s = userService.saveUser(user.getName());
        System.out.println("mock service log:" + s);
        return s;
    }

    @DeleteMapping("/user")
    public String deleteUser(Integer id) {
        Integer integer = userDao.deleteById(id);
        return String.format("执行结果：成功删除【%d】条数据", integer);
    }

    @PostMapping("/user/private")
    public String testPrivate() {
        String s = userService.userPrivateMethod("test");
        System.out.println("mock service log:" + s);
        return s;
    }

}
